package cn.wdm.ymcc.service.impl;

import cn.wdm.ymcc.domain.PayOrder;
import cn.wdm.ymcc.mapper.PayOrderMapper;
import cn.wdm.ymcc.service.IPayOrderService;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.common.models.AlipayTradeCloseResponse;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lao.zhang
 * @since 2022-07-31
 */
@Service
public class PayOrderServiceImpl extends ServiceImpl<PayOrderMapper, PayOrder> implements IPayOrderService {
    /**
     * 根据订单号查询支付单
     * @param orderNo
     * @return
     */
    @Override
    public PayOrder selectByOrderNo(String orderNo) {
        Wrapper<PayOrder> wrapper=new EntityWrapper<PayOrder>();
        wrapper.eq("order_no",orderNo);
        PayOrder payOrder = selectOne(wrapper);
        return payOrder;
    }
    /**
     * 支付超时，处理支付单
     * @param courseOrderNo
     */
    @Override
    public void cancelPayOrder(String courseOrderNo) {
        PayOrder payOrder = selectByOrderNo(courseOrderNo);
        //取消支付单
        if(payOrder.getPayStatus().intValue() == PayOrder.STATE_WAIT_PAY){
            payOrder.setPayStatus(PayOrder.STATE_CANCEL);
            updateById(payOrder);
        }
        //调用支付宝，关闭支付
        try {
            AlipayTradeCloseResponse close = Factory.Payment.Common().close(courseOrderNo);
        } catch (Exception e) {
            e.printStackTrace();
            /**
             * 做兜底
             * 1.重试3次
             * 2.保存要取消支付单的记录到数据库，运维人员来人工跟进
             * 3.给运维人员发站内信，邮件，消息---- 对接钉钉推销
             */
        }
    }

}
